package com.sy.service.impl.inventory;

import com.sy.bean.inventory.Allocate;
import com.sy.common.crud.BaseServiceImpl;
import com.sy.common.exception.BusinessException;
import com.sy.mapper.inventory.AllocateMapper;
import com.sy.service.inventory.AllocateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class AllocateServiceImpl extends BaseServiceImpl<Allocate, AllocateMapper> implements AllocateService {

    @Autowired
    AllocateMapper allocateMapper;

    String currentMaxCode; //当前最大编码 CG2024001
    @Override
    public List<Allocate> queryById(int id) {
        List<Allocate> list= allocateMapper.queryById(id);
        return list;
    }

    @Override
    public int examineById(String reviewers,int id,int type) {
        int rs = allocateMapper.examineById(reviewers,id,type);
        if (rs == 0){
            throw new BusinessException("审核失败");
        }
        return rs;
    }

    @Transactional
    @Override
    public int insertAllocate(Allocate allocate) {
        allocate.setCode(generateCode());
        int rs = allocateMapper.insertAllocate(allocate);
        if (rs == 0){
            throw new BusinessException("新增调拨单失败");
        }
        rs = allocateMapper.insertAllocateDetail(allocate.getId(),allocate.getAllocateDetailList());
        if (rs == 0){
            throw new BusinessException("新增调拨单明细失败");
        }
        return rs;
    }

    String generateCode() {
        String year = getYear();
        //判断当前最大编码是否存在
        if (null == currentMaxCode) {
            //如果不存在，查询当年最大编码
            currentMaxCode = baseMapper.queryMaxCode(year);
            if (null == currentMaxCode) {
                //说明不存在，生产第一个编码
                currentMaxCode = "DB" + year + "001";
            } else {
                //如果存在，新编码序号+1
                getNextCode();
            }
        } else {
            //如果存在，新编码序号+1
            getNextCode();
        }
        return currentMaxCode;
    }

    void getNextCode() {
        //CG2024001
        String prefix = currentMaxCode.substring(0, 6);
        String seq = currentMaxCode.substring(6);
        //转换数字001. tmp=1
        int tmp = Integer.parseInt(seq);
        tmp++;
        currentMaxCode = prefix + String.format("%03d", tmp);
    }

    String getYear() {
        LocalDate localDate = LocalDate.now();
        return String.valueOf(localDate.getYear());
    }


}
